<template>
  <div class="search">
    <!-- 顶部 -->
    <van-nav-bar title="搜索中心">
      <span slot="left" @click="$router.go(-1)">
        <i slot="icon" class="iconfont icon-zhiyuanfanhui17"></i>
      </span>
    </van-nav-bar>
    <!-- 内容部分 -->
    <van-pull-refresh class="content" @refresh="onRefresh" v-model="isLoading" success-text="正在刷新">
      <!-- 搜索部分 -->
      <van-search v-model="searchVal" placeholder="搜索你喜欢的商品" show-action @search="onSearch">
        <div slot="action" @click="onSearch()">搜索</div>
      </van-search>
      <!-- 历史记录 -->
      <div class="history">
        <div class="history_title" v-if="OKgoods.length==0">
          <span>搜索历史</span>
          <span @click="clearHistory">
            <i class="iconfont icon-delete"></i>清空记录
          </span>
        </div>
        <ul class="history_list" v-if="OKgoods.length==0">
          <li v-for="item in historyList" :key="item">
            {{item}}
            <i class="iconfont icon-cha" @click="DelCurrent(item)"></i>
          </li>
        </ul>

        <!-- 卡片头部 -->
        <ul class="card_title" v-if="OKgoods.length>0">
          <li>上架时间
            <i class="iconfont icon-xia1"></i>
          </li>
          <li>价格
            <i class="iconfont icon-xia1"></i>
          </li>
          <li>销量
            <i class="iconfont icon-xia1"></i>
          </li>
          <li>折扣
            <i class="iconfont icon-xia1"></i>
          </li>
        </ul>
        <!-- 卡片 -->
        <van-list
          v-model="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad">
          <div class="shop_card" v-for="item in OKgoods" :key="item.id">
            <img :src="'http://127.0.0.1:3000'+item.pic[0].picAddr">
            <div class="text">{{item.proName}}</div>
            <div class="price">
              <span>￥{{item.price}}</span>
              <s>￥{{item.oldPrice}}</s>
            </div>
            <button @click="jumpToDetail(item.id)">立即购买</button>
          </div>
        </van-list>
      </div>
    </van-pull-refresh>
    <!-- 底部标签页 -->
    <van-tabbar v-model="active" active-color="#ff8c00">
      <van-tabbar-item icon="home-o" @click="jumpToHome">首页</van-tabbar-item>
      <van-tabbar-item>
        <i slot="icon" class="iconfont icon-caidan1" @click="jumpToCate"></i>分类
      </van-tabbar-item>
      <van-tabbar-item>
        <i slot="icon" class="iconfont icon-ai-cart"></i>购物车
      </van-tabbar-item>
      <van-tabbar-item>
        <i slot="icon" class="iconfont icon-huiyuan21"></i>会员中心
      </van-tabbar-item>
    </van-tabbar>
  </div>
</template>

<script>
import { queryProduct } from '@/api'
export default {
  data () {
    return {
      active: -1,
      searchVal: '',
      queryHistory: [], // 存放请求回来的商品信息
      OKgoods: [], // 匹配搜索的商品
      historyList: [], // 存放本地存储的历史搜索记录
      isLoading: false,
      loading: false, // 上拉加载的组件
      finished: true
    }
  },
  created () {
    // console.log(this.searchVal)
    // 初始化搜索历史
    this.initQueryHistory()
    // console.log(this.OKgoods)
    // console.log(typeof localStorage.getItem('queryHistory'))
  },
  methods: {
    // 点击搜索执行的方法
    onSearch (cb) {
      // 判断是否为空输入值
      if (!this.searchVal) {
        this.$nextTick(() => {
          this.isLoading = false
        })
        this.$toast.fail('请输入关键字')
        // cb && cb()
        return
      }
      // 发送请求数据之前,清空OKgoods,否则再次点击会导致id重复,出bug
      this.OKgoods = []
      // 存入之前,先判断是否有重复,有重复则删除旧历史记录
      // 每次点击搜索,都要把搜索的值存入本地存储当中
      let arr = JSON.parse(localStorage.getItem('queryHistory') || '[]')
      // console.log(arr)

      arr.forEach((item, index, array) => {
        if (item === this.searchVal) {
          arr.splice(index, 1)
        }
      })

      arr.unshift(this.searchVal)
      localStorage.setItem('queryHistory', JSON.stringify(arr))

      queryProduct({ page: 1, pageSize: 10 }).then(res => {
        // console.log(123)
        // console.log(res)
        // 存放请求回来的所有数组
        this.queryHistory = res.data.data
        // console.log('返回值', res.data.data)
        // 遍历请求回来的数据的数组,判断是否符合输入的值
        this.queryHistory.forEach((item, index, array) => {
          // console.log(item)
          let isOk = item.proName.search(this.searchVal)
          if (isOk !== -1) {
            // 拿到符合条件的值的数组
            this.OKgoods.push(item)
          }
        })
        if (this.OKgoods.length === 0) {
          this.$toast.fail('没有相关商品信息')
          this.initQueryHistory()
        }
        cb && cb()
      })
    },
    // 初始化搜索历史的方法
    initQueryHistory () {
      this.historyList = JSON.parse(localStorage.getItem('queryHistory'))
    },
    // 清空历史记录的方法
    clearHistory () {
      // localStorage.setItem('queryHistory', '')
      localStorage.clear()
      this.initQueryHistory()
    },
    // 下拉刷新的方法
    onRefresh () {
      this.onSearch(() => {
        this.$toast('刷新成功')
        this.isLoading = false
      })
    },
    // 上拉加载的方法
    onLoad () {
      if (this.OKgoods.length >= 10) {
        this.finished = false
        this.queryProduct({ page: 2, pageSize: 10 })
          .then(res => {
            // 将请求的第二页数据追加到queryHistory里
            this.queryHistory.push(res.data.data)
            this.queryHistory.forEach((item, index, array) => {
              // console.log(item)
              let isOk = item.proName.search(this.searchVal)
              if (isOk !== -1) {
                // 拿到符合条件的值的数组
                this.OKgoods.push(item)
              }
            })
            this.finished = true
          })
      } else {
        this.finished = true
      }
    },
    // 删除当前行历史记录的方法
    DelCurrent (item) {
      let currentLine = JSON.parse(localStorage.getItem('queryHistory'))
      currentLine.splice(currentLine.indexOf(item), 1)
      localStorage.setItem('queryHistory', JSON.stringify(currentLine))
      this.initQueryHistory()
    },
    jumpToCate () {
      this.$router.push({ name: 'category' })
    },
    jumpToHome () {
      this.$router.push({ name: 'home' })
    },
    jumpToInfo () {
      this.$router.push({ name: 'userinfo' })
    },
    jumpToDetail (id) {
      // console.log(id)
      this.$router.push({ name: 'product', params: { id } })
    }
  }
}
</script>

<style lang="scss" scoped>
  .content {
    margin-bottom: 50px;
    padding: 0 10px 10px;
    .van-search {
      background: none !important;
      padding: 10px 0;
      .van-cell--borderless {
        border: 1px solid #006699;
        line-height: 22px;
      }
      .van-search__action {
        width: 40px;
        text-align: center;
        background-color: #006699;
        color: #fff;
        border-radius: 4px;
      }
    }
  }
</style>

<style lang="scss" scoped>
  .search {
    .van-nav-bar {
      background-color: #006699;
      .van-nav-bar__title {
        color: #fff;
        font-size: 17px;
        font-weight: blod;
      }
      .icon-zhiyuanfanhui17 {
        color: #fff;
        font-size: 17px;
      }
    }
    .history {
      font-size: 12px;
      color: #666;
      .history_title {
        display: flex;
        justify-content: space-between;
      }
      .history_list {
        li {
          border: 1px solid #ccc;
          padding: 6px 10px;
          margin-top: 12px;
          .icon-cha {
            float: right;
          }
        }
      }
      .card_title {
        margin: 10px 0;
        height: 30px;
        line-height: 30px;
        background-color: #eee;
        display: flex;
        justify-content: space-around;
      }
      .shop_card {
        float: left;
        width: 47%;
        box-shadow: 0 0 5px 0px #ccc;
        margin: 5px;
        img {
          width: 100%;
        }
        .text {
          font-size: 14px;
          color: #8f8f94;
          padding: 0 10px;
          height: 35px;
          overflow: hidden;
        }
        .price {
          font-size: 12px;
          display: flex;
          justify-content: space-around;
          padding: 0 30px;
          margin: 10px 0;
          span {
            color: red;
          }
          s {
            color: #ccc;
          }
        }
        button {
          background-color: #006699;
          color: #fff;
          border: none;
          display: block;
          margin: 0 auto;
        }
      }
    }
    //底部标签页
    .van-hairline--top-bottom {
      background-color: #006699;
      .van-tabbar-item {
        color: #fff;
      }
    }
  }
</style>
